package com.sunronsoft.mind.map;

import com.jfinal.captcha.CaptchaRender;
import com.jfinal.core.Controller;
import com.jfinal.kit.HashKit;
import com.jfinal.kit.JsonKit;
import com.jfinal.kit.Kv;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.ehcache.CacheKit;

/**
 * @author Sunron
 **/
public class IndexController extends Controller {
    
    private static UserService userService = UserService.getInstance();
    
    public void index() {
        render("index.html");
    }

    public void captcha() {
        render(new MyCaptchaRender());
    }
    
    public void mind() {
        render("mind-map.html");
    }
    
    public void login() {
        Kv params = JsonKit.parse(getRawData(), Kv.class);
        if (params == null || params.isEmpty()) {
            renderJson(DataKit.toFail("登录失败，请输入登录账号和密码"));
        } else if (!params.containsKey("vercode") || StrKit.isBlank(params.getStr("vercode"))) {
            renderJson(DataKit.toFail(1000, "请输入验证码"));
        } else if (!CaptchaRender.validate(this, params.getStr("vercode"))) {
            renderJson(DataKit.toFail(1000, "验证码错误"));
        } else if (!params.containsKey("account") || !params.containsKey("password")) {
            renderJson(DataKit.toFail("登录失败，请输入登录账号和密码"));
        } else {
            String userName = params.getStr("account").trim();
            String password = params.getStr("password").trim();
            password = HashKit.md5(password);
            
            Kv user = userService.login(userName, password);
            if (null == user || user.isEmpty()) {
                renderJson(DataKit.toFail("登录失败，账号或密码错误"));
            } else {
                CacheKit.put("authorizationCache", getSession().getId(), user);
                renderJson(DataKit.toSuccess(user));
            }
        }
    }

    public void logout() {
        CacheKit.remove("authorizationCache", getSession().getId());
        renderJson(DataKit.toSuccess(1001, "成功退出"));
    }
    
    public void main() {
        render("main.html");
    }
}
